﻿using System.Linq;
using System.Web.Mvc;

using Umbraco.Framework;
using Umbraco.Framework.Persistence.Model;
using Umbraco.Framework.Persistence.Model.Constants;
using Umbraco.Hive;
using Umbraco.Hive.RepositoryTypes;

namespace idseefeld.com.imagecropper
{
	public static class UmbracoHelper
	{
		/// <summary>
		/// get TypedEntity by HiveId
		/// based on function in Umbraco.Cms.Web.UrlHelperExtensions GetMediaUrl(this UrlHelper url, HiveId id, string propertyAlias, int size)
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public static TypedEntity GetEntiyByHiveId(HiveId id)
		{
			TypedEntity result = null;
			if (id.IsNullValueOrEmpty())
				return result;

			var hive = DependencyResolver.Current.GetService<IHiveManager>();
			// We have to handle User/Member entities slightly differently
			if (id.ProviderGroupRoot.AbsoluteUri.StartsWith("security://"))
			{
				using (var uow = hive.OpenReader<ISecurityStore>(id.ToUri()))
				{
					var item = uow.Repositories.OfRevisionType(FixedStatusTypes.Published).FirstOrDefault(x => x.Id == id);

					if (item != null) result = item;
				}
			}
			else
			{
				using (var uow = hive.OpenReader<IContentStore>(id.ToUri()))
				{
					var item = uow.Repositories.OfRevisionType(FixedStatusTypes.Published).FirstOrDefault(x => x.Id == id);

					if (item != null) result = item;

				}
			}

			return result;
		}
	}
}
